# application/api/system/communication.py
from flask import Blueprint, jsonify, request
import serial.tools.list_ports

from application.services.system.communication import CommunicationService
from application.utils.res import json_fail, json_success

# 创建蓝图
bp = Blueprint("communication", __name__, url_prefix="/communication")


@bp.get("/serial/list")
def get_serial_list():
    ports = []
    for port in serial.tools.list_ports.comports():
        ports.append({
            'device': port.device,
            'description': port.description,
        })
    return json_success(ports)


@bp.post("/connect")
def communication_connect():
    """
    通讯测试接口
    请求参数:
    - type: 通讯类型 (serial, tcp, modbus, bluetooth)
    - config: 配置参数 (根据通讯类型不同而不同)
    """
    try:
        data = request.get_json()
        communication_type = data.get('communicationType')

        if not communication_type:
            return json_fail("请选择通讯类型")
        # 连接串口通讯
        if communication_type == '1' or communication_type == '2' :
            res = CommunicationService.connect_serial(data)
            return json_success(res, '连接成功')
        
        # 连接TCP通讯
        if communication_type == '3':
            CommunicationService.connect_tcp(data)


    except Exception as e:
        return json_fail(f"连接失败: {str(e)}"), 500
    
@bp.post("/close")
def communication_close():
    """
    通讯测试接口
    请求参数:
    - type: 通讯类型 (serial, tcp, modbus, bluetooth)
    - config: 配置参数 (根据通讯类型不同而不同)
    """
    try:
        data = request.get_json()
        communication_type = data.get('communicationType')

        if not communication_type:
            return json_fail("请选择通讯类型")
        # 连接串口通讯
        if communication_type == '1' or communication_type == '2' :
            res = CommunicationService.close_serial()
            return json_success(res, '断开连接成功')
        
        # 连接TCP通讯
        if communication_type == '3':
            CommunicationService.connect_tcp(data)


    except Exception as e:
        return json_fail(f"连接失败: {str(e)}"), 500

@bp.post("/send")
def communication_send():
    """
    通讯测试接口
    请求参数:
    - type: 通讯类型 (serial, tcp, modbus, bluetooth)
    - config: 配置参数 (根据通讯类型不同而不同)
    """
    try:
        data = request.get_json()
        communication_type = data.get('communicationType')

        if not communication_type:
            return json_fail("请选择通讯类型")
        # 连接串口通讯
        if communication_type == '1' or communication_type == '2' :
            res = CommunicationService.send_serial_data(data)
            return json_success(res, '连接成功')
        
        # 连接TCP通讯
        if communication_type == '3':
            CommunicationService.connect_tcp(data)


    except Exception as e:
        return json_fail(f"连接失败: {str(e)}"), 500